/*
 * @Author: kakay
 * @Date: 2017-08-17 14:49:18
 * */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Flex, Drawer, NavBar, InputItem, List, ListView, Button, Picker, DatePicker, Popup , Icon } from 'antd-mobile';
import { Resource } from '../../../service/resource';
import BrowserUtils from '../../../service/history';
import './index.scss';

const Item = List.Item;

export default class LogList extends Component {
  constructor(props) {
    super(props);
    const data = props.location.state && props.location.state.data;
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      logList : [],
      start: 0,
      open: false,
      serachFlag: false,
      num: 10,
      dataSource: dataSource.cloneWithRows([]),
      refreshing: false,
      height: document.documentElement.clientHeight,
      serach: {
        start: 0,
        num: 10
      },
        optionList:data||[],
        sValue:'',
        sName:'',

        logDetail:{},
        userList:[],
        uValue:'',
        uName:'',
    };
    
  }

  componentDidMount() {
    this.hasMore = true;
    this.manuallyRefresh = true;
    this.getLogList()
    this.getProject();
    this.getUsers();
    this.setState({height: this.state.height - ReactDOM.findDOMNode(this.refs.lv).offsetTop,})
  }


  getProject (){
    Resource.getProjects.get().then(res => {
      let Value = res[0].id;
      let Name = res[0].name;
      let arr = [];
      res.map((item, index) =>
      arr.push({
        label:item.name,
        value:item.id,
      })
      ) 
      this.setState({
        optionList: arr,
        sValue: Value,
        sName: Name,
       
      })
    }) 
  }

  componentWillReceiveProps(nextProps) {
    this.getLogList();
    if (nextProps.location.state && nextProps.location.state.data) {
      this.setState({optionList: nextProps.location.state.data});
    }
  }

  getLogList (){
    const {start,num, dataSource} = this.state;
    Resource.getRecordList.get({start:start,num:num}).then(res => {
      this.setState({
        logList:res, 
        dataSource: dataSource.cloneWithRows(res),
        start: start ,
        num: num 
      })
    });
  }
  getUsers (){
    Resource.getUsers.get().then(res => {
      let arr = []
      res.map((item, index) =>
      arr.push({
        label:item.userName,
        value:item.id,
      })
      ) 
      arr.unshift({
        label:"不限",
        value:"",
      })
      this.setState({
        userList: arr
       
      })
    });
  }
  

  componentWillUnmount() {
    this.refs.lv.getInnerViewNode().removeEventListener('touchstart', this.ts);
    this.refs.lv.getInnerViewNode().removeEventListener('touchmove', this.tm);
  }
  onScroll = (e) => {
    this.st = e.scroller.getValues().top;
    this.domScroller = e;
  }
  onOpenChange = (...args) => {
    this.setState({ open: !this.state.open });
  }

  onTouchTapBack() {
    BrowserUtils.goBack();
  }

  // input值获取
  editInfo(value, type){
    const { serach } = this.state;
    if (type === 'userName') {
      serach.userID = value;
    }
    this.setState({serach});
  }

  onRefresh = () => {
    const {start,num, dataSource} = this.state;
    if (this.hasMore) {
      this.hasMore = false;
      Resource.getRecordList.get({start:start,num:num}).then(res => {
        this.setState({
          logList: res,
          dataSource: dataSource.cloneWithRows([...res]),
          refreshing: false,
          start: start + 10,
          num: num + 10,
          serachFlag: false
        });
        this.hasMore = true;
      });
    }
  }

  selectProject(value) {
    const {optionList} = this.state;
    let Name="";
       optionList.forEach(item => {
          if(item.value ===value[0]) {
           Name = item.label
          }
       })
       this.setState({
        sName:Name,
        sValue:value
       })

  }

  selectUser(value) {
    const {userList} = this.state;
    let Name="";
    userList.forEach(item => {
          if(item.value ===value[0]) {
            Name = item.label
          }
       })
       this.setState({
        uName:Name,
        uValue:value
       })

  }
  //  日志搜索
  onGetLogList(){
    console.log(this.state)
    const {serach, dataSource} =this.state;
    if(this.state.dpValue&&this.state.dpValue!==""){
      serach.date = this.state.dpValue.format('YYYY-MM-DD')
    }
    if(this.state.sValue!==""){
      let sValuePro = this.state.sValue
      serach.projectID = sValuePro
    }
    if(this.state.uValue!==""){
      let uValueUse = this.state.uValue
      serach.userID = uValueUse[0]
    }
    Resource.getRecordList.get(serach).then(res => {
      this.setState({
        logList:res,
        dataSource: dataSource.cloneWithRows(res),
        serachFlag: true
      });
      this.onOpenChange();
    })
  }

  deleteLog = (id,sel) => {
    this.setState({ sel });
    Resource.deleteRecord.get({id:id}).then(res => {
      this.getLogList()
      Popup.hide();
    })
  };

  onClose = (sel) => {
    this.setState({ sel });
    Popup.hide();
  };

  renderHeader = () => (
    <div style={{ position: 'relative' }}>
      日志详情
      <span
        style={{
          position: 'absolute', right: 3, top: -5,
        }}
        onClick={(v) => this.onClose('close')}
      >
        <Icon type="cross" />
      </span>
    </div>
  );

  detailLog(id){
    Resource.getOneRecord.get({id:id}).then(res => {
      Popup.show(<div>
        <List renderHeader={this.renderHeader}
          className="popup-list"
        >
        <List.Item>项目时间 : {res.date}</List.Item>
        <List.Item>操作时间 : {res.optDate}</List.Item>
        <List.Item>项目纪录 : {res.record}</List.Item>
        <List.Item>项目工时 : {res.workingHour}</List.Item>
        </List>
        <ul style={{ padding: '0.18rem 0.3rem', listStyle: 'none' }}>
          <li style={{ marginTop: '0.18rem' }}>
            <Button type="primary" onClick={(v) => this.deleteLog(res.id, 'cancel')}>删除</Button>
          </li>
        </ul>
      </div>, { animationType: 'slide-up',  maskClosable: false });
    })
  }
    
  separator(sectionID, rowID) {
    return (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 5,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    )
  }

  sidebar() {
    return (
      <Flex direction="column" align="center">
        <Flex className="inputItem" justify="between">
          <Flex.Item className="label">项目:</Flex.Item>
          <Picker
          data={this.state.optionList}
          title="选择项目"
          cols={1}
          editable={false}
          extra={""}
          value={this.state.sValue}
          onChange={v => this.selectProject(v)}
        >
        <InputItem   
          className="pickerInput"
           extra=""
          value = {this.state.sName}
          placeholder="请输入项目名称"/>
        </Picker>
        </Flex>
        <Flex className="inputItem" justify="between">
          <Flex.Item className="label">日期:</Flex.Item>
          <InputItem
          className="input"
          value={this.state.dpValue && this.state.dpValue.format('YYYY-MM-DD')}
          clear
          editable={false}
          placeholder="请输入日期"
          onClick={() => this.setState({ visible: true })}
          onChange={value => this.editInfo(value, 'logDate')}
          />
        <DatePicker
          visible={this.state.visible}
          mode="date"
          title={<span onClick={() => this.setState({ visible: false })}>点击可以关闭</span>}
          extra="请选择(可选)"
          onOk={() => console.log(this.state.dpValue)}
          onDismiss={() => this.setState({ visible: false })}
          value={this.state.dpValue}
          onChange={v => this.setState({ dpValue: v, visible: false })}
        />
        </Flex>
        <Flex className="inputItem" justify="between">
          <Flex.Item className="label">用户名:</Flex.Item>
          <Picker
          data={this.state.userList}
          title="选择用户名"
          cols={1}
          extra={""}
          value={this.state.uValue}
          onChange={v => this.selectUser(v)}
        >
        <InputItem   
          className="pickerInput"
           extra=""
           editable={false}
          value = {this.state.uName}
          placeholder="请选择用户名"/>
        </Picker>
        </Flex>
        <Flex className="inputItem" justify="around">
          <Button className="btn" type="primary" onTouchTap={(e)=>this.onGetLogList(e)}>查询</Button>
        </Flex>
      </Flex>
    )
  }
    
  render() {
    const row = (rowData, sectionID, rowID) => {
      const date = rowData.date && (rowData.date.split('-')[1] + '-' + rowData.date.split('-')[2]);
      return (
         <Flex key={rowID} justify="between" className="lv-item" onTouchTap = {(e) => this.detailLog(rowData.id)}>
          <Flex.Item className="label">{rowData.projectName}</Flex.Item>
          <Flex.Item className="label">{rowData.nickName}</Flex.Item>
          <Flex.Item className="label">{rowData.workingHour}</Flex.Item>
          <Flex.Item className="label">{date}</Flex.Item>
        </Flex>
      );
    }

    const sidebar = this.sidebar();
    return (
      <Flex className="loglist" direction="column" align="start" style={{display: this.props.display}}>
        <NavBar
          mode="dark"
          className="am-tab-bar-bar"
          style={{top: 0}}
          onLeftClick={() => this.onTouchTapBack()}
          rightContent={[
            <div key="0" onClick={() => this.onOpenChange()}>查询</div>
          ]}
        >
        日志列表
        </NavBar>
        <Flex className="content" direction="column" align="center">
          <Drawer
            className="my-drawer"
            style={{ minHeight: document.documentElement.clientHeight - 200 }}
            sidebar={sidebar}
            position="right"
            open={this.state.open}
            >
            查询
          </Drawer>
          <List className="my-list">
            <Item onLongPress={this.handleLongPress} style={{background: '#ddd'}}>
              <Flex justify="between">
                <Flex.Item className="label">项目</Flex.Item>
                <Flex.Item className="label">姓名</Flex.Item>
                <Flex.Item className="label">工时</Flex.Item>
                <Flex.Item className="label">日期</Flex.Item>
              </Flex>
            </Item>
          </List>
          <ListView
            ref="lv"
            className="list-view"
            dataSource={this.state.dataSource}
            renderRow={row}
            renderSeparator={this.separator}
            initialListSize={10}
            pageSize={10}
            scrollRenderAheadDistance={200}
            renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
              {this.state.refreshing ? 'Loading...' : 'Loaded'}
            </div>)}
            scrollEventThrottle={20}
            style={{
              height: this.state.height,
              border: '1px solid #ddd',
              margin: '0.1rem 0',
            }}
            scrollerOptions={{ scrollbars: true }}
            onEndReached={!this.state.serachFlag ? this.onRefresh : (() => {}) }
          />
        </Flex>
      </Flex>
      
    );
  }
}

